//
//  PersonalStatusViewController.m
//  tcpoctest
//
//  Created by sun on 13-4-6.
//  Copyright (c) 2013年 gump. All rights reserved.
//

#import "PersonalStatusViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "EGOPhotoGlobal.h"
#import "MyPhotoSource.h"
#import "MyPhoto.h"
#import "FirCirLocalResourceDataSource.h"

#import "FirCirPersonDataSource.h"
#import "FirCirNewsDataSource.h"
#import "FirCirBgImageDataSource.h"
#import "FirendCircleDataSource.h"

#import "sendFirCirGetAllComment.h"

@interface PersonalStatusViewController ()
{
    UIImageView *backgroundImageView;
    UITableView *statusTable;
    UIImageView *headIV;
}

@property (nonatomic, strong) NSArray *urlArray;

@end

@implementation PersonalStatusViewController

-(id)init
{
    self = [super init];
    
    if (self != nil) {
        iTimeCount = 0;
        iGameState = VGS_NULL;
    }
    
    return self;
}

-(void)initUI
{
    self.view.backgroundColor = VIEW_BG_COLOR;
    
    [self createTitle];
    
    if ([DataControl shareControl].currentFI != nil) {
        self.mtitle.text = [DataControl shareControl].currentFI.name;;
    }else{
        UIAlertView *errorAlert = [[UIAlertView alloc]initWithTitle:@"抱歉" message:@"获取空间信息失败，请稍后再试。" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [errorAlert show];
    }
    UIBarButtonItem *backItem = [self createBarBackButtonItemWithTitle:@"返回" target:self action:@selector(backButtonPressed)];
    self.navItem.leftBarButtonItem = backItem;
    
    UIBarButtonItem *nextItem = [self createBarButtonItemWithTitle:@"发布新动态"
                                                            target:self
                                                            action:@selector(writeNewStatus:)];
    self.navItem.rightBarButtonItem = nextItem;
    
    
    NSString *backgroundImagestr = [[DataControl shareControl].fcBgImageDS SearchFCBgImageByMail:
                                [DataControl shareControl].currentFI.mail];
    UIImage *backgroundImage = nil;
    
    if (backgroundImagestr == nil || [backgroundImagestr isEqualToString:@""]) {
        backgroundImage = [UIImage imageNamed:@"cover1.jpg"];
    }
    else
    {
        backgroundImage = [UIImage imageWithContentsOfFile:backgroundImagestr];
    }
    
    CGRect backgroundRect = CGRectMake(0, 0, 320, 320);
    backgroundImageView = [[UIImageView alloc] initWithFrame:backgroundRect];
    backgroundImageView.image = backgroundImage;
    backgroundImageView.contentMode = UIViewContentModeScaleAspectFill;
    backgroundImageView.userInteractionEnabled = YES;
    
    headIV = [[UIImageView alloc]initWithFrame:CGRectMake(18, 69, 58, 58)];

    NSString *imageurl = [[DataControl shareControl] SearchHeadImage:
                          [DataControl shareControl].currentFI.mail];
    
    UIImage *headImg;
    if ([imageurl length] > 0)
    {
        headImg = [UIImage imageWithContentsOfFile:imageurl];
    }
    else
    {   
        headImg = [UIImage imageNamed:@"default_head.png"];
    }
    
    [self updatePlayerHeadImage:headImg];
    
    [backgroundImageView addSubview:headIV];
    
    statusTable = [[UITableView alloc]initWithFrame:CGRectMake(0, TOPBAR_HIGHT,
                                                               WINDOW_WIDTH,
                                                               WINDOW_HIGTH - TOPBAR_HIGHT - 20)
                                              style:UITableViewStylePlain];
    statusTable.dataSource = self;
    statusTable.delegate = self;
    statusTable.tableHeaderView = backgroundImageView;
    [self.view addSubview:statusTable];
}

- (void)updatePlayerHeadImage:(UIImage*)headImg
{
    UIImage *finalImage = nil;
    UIGraphicsBeginImageContext(headImg.size);
    {
        CGContextRef ctx = UIGraphicsGetCurrentContext();
        CGAffineTransform trnsfrm = CGAffineTransformConcat(CGAffineTransformIdentity, CGAffineTransformMakeScale(1.0, -1.0));
        trnsfrm = CGAffineTransformConcat(trnsfrm, CGAffineTransformMakeTranslation(0.0, headImg.size.height));
        CGContextConcatCTM(ctx, trnsfrm);
        CGContextBeginPath(ctx);
        CGContextAddEllipseInRect(ctx, CGRectMake(0.0, 0.0, headImg.size.width, headImg.size.height));
        CGContextClip(ctx);
        CGContextDrawImage(ctx, CGRectMake(0.0, 0.0, headImg.size.width, headImg.size.height), headImg.CGImage);
        finalImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    headIV.image = finalImage;
}

-(void)backButtonPressed
{
    [[ViewManager sharedViewManager] backView:self];
}

- (void)writeNewStatus:(id)sender
{
    [[ViewManager sharedViewManager] showView:VI_WRITESTATUS
                             withIsRemoveCurV:false
                                withDirection:VD_RIGHT];
}

- (void)imageButtonClicked:(int)btnTag
{
    if ([[DataControl shareControl].fcPersonDS Curshow] == nil) {
        return;
    }
    
    NSString *newsid = [[DataControl shareControl].fcPersonDS CurShowObjectByIndex:btnTag];
    FriendStatus *status = [[DataControl shareControl].fcnewsDS getNewsByID:newsid];
    if (status == nil) {
        return;
    }
    
    NSMutableArray *photos = [[NSMutableArray alloc]init];
    for (int imgCnt = 0; imgCnt < [status.imageIDArray count]; imgCnt++) {
        NSString *picid = [status.imageIDArray objectAtIndex:imgCnt];
        NSString *imgUrl = [[DataControl shareControl].fcLocalRecDS getRcLocalPathByID:picid];
        if (imgUrl != nil && ![imgUrl isEqualToString:@""]) {
            MyPhoto *photo = [[MyPhoto alloc] initWithImage:[UIImage imageWithContentsOfFile:imgUrl]];
            [photos addObject:photo];
        }
    }
    MyPhotoSource *source = [[MyPhotoSource alloc] initWithPhotos:photos];
    EGOPhotoViewController *photoController = [[EGOPhotoViewController alloc] initWithPhotoSource:source];
    UINavigationController *navController =
    [[UINavigationController alloc] initWithRootViewController:photoController];
    
    navController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    navController.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:navController animated:YES completion:nil];
}

-(void)ImageArrBtnClicked:(int)btnTag withImageTag:(int)imageTag
{
    NSString *fi = [[DataControl shareControl].fcPersonDS CurShowObjectByIndex:btnTag];
    
    FriendStatus *status = [[DataControl shareControl].fcnewsDS getNewsByID:fi];
    
    if (status != nil) {
        NSMutableArray *photos = [[NSMutableArray alloc]init];
        for (int imgCnt = 0; imgCnt < [status.imageIDArray count]; imgCnt++) {
            NSString *picid = [status.imageIDArray objectAtIndex:imgCnt];
            NSString *imgUrl = [[DataControl shareControl].fcLocalRecDS getRcLocalPathByID:picid];
            if (![imgUrl isEqualToString:@""]) {
                MyPhoto *photo = [[MyPhoto alloc] initWithImage:[UIImage imageWithContentsOfFile:imgUrl]];
                [photos addObject:photo];
            }
        }
        MyPhotoSource *source = [[MyPhotoSource alloc] initWithPhotos:photos];
        EGOPhotoViewController *photoController = [[EGOPhotoViewController alloc] initWithPhotoSource:source];
        UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:photoController];
        
        navController.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        navController.modalPresentationStyle = UIModalPresentationFullScreen;
        [self presentViewController:navController animated:YES completion:nil];
        
        if (imageTag >= 0 && imageTag < status.imageIDArray.count) {
            [photoController moveToPhotoAtIndex:imageTag animated:NO];
        }
    
    }
}

#pragma mark -private fun-
-(void)refreshView
{
    NSString *backgroundImagestr = [[DataControl shareControl].fcBgImageDS SearchFCBgImageByMail:
                                    [DataControl shareControl].currentFI.mail];
    
    if (backgroundImagestr != nil && ![backgroundImagestr isEqualToString:@""]) {
        backgroundImageView.image = [UIImage imageWithContentsOfFile:backgroundImagestr];
    }
    else
    {
        backgroundImageView.image = [UIImage imageNamed:@"fircirbg.jpg"];
    }
    
    NSString *imageurl = [[DataControl shareControl] SearchHeadImage:
                          [DataControl shareControl].currentFI.mail];
    if ([imageurl length] > 0)
    {
        headIV.image = [UIImage imageWithContentsOfFile:imageurl];
        [self updatePlayerHeadImage:headIV.image];
    }
    
    if ([DataControl shareControl].currentFI != nil) {
        self.mtitle.text = [DataControl shareControl].currentFI.name;
        
        [[DataControl shareControl].fcPersonDS setCurshow:
         [[DataControl shareControl].fcPersonDS getShowArrByMail:
          [DataControl shareControl].currentFI.mail]];
        
        [[DataControl shareControl].fcPersonDS SortCurShow];
    }
    
    [statusTable reloadData];
}

-(void)viewWillShow
{
    [self refreshView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)BeginDelNew
{
    iTimeCount = 0;
    iGameState = VGS_START;
    
    [[ViewManager sharedViewManager] showProgressHUDWithStatus:@"正在删除..."
                                                      withView:self.view];
}

-(void)EndDelNew
{
    if (iGameState == VGS_START) {
        [[ViewManager sharedViewManager] ChangeHUDShowSuccess:@"删除成功!"];
        
        iTimeCount = 0;
        iGameState = VGS_NULL;
    }
}

-(void)UICustomTick
{
    switch (iGameState) {
        case VGS_START:
        {
            if (iTimeCount < 150) {
                iTimeCount++;
            }
            else
            {
                iTimeCount = 0;
                iGameState = VGS_NULL;
                
                [[ViewManager sharedViewManager] dismissProgressHUD];
            }
        }
            break;
            
        default:
            break;
    }
}

-(void)PackUpCell
{
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:[DataControl shareControl].fircirDS.iPackupRow
                                              inSection:[DataControl shareControl].fircirDS.iPackupSection];
    [statusTable reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil]
                       withRowAnimation:UITableViewRowAnimationNone];
    
    
    if ([DataControl shareControl].fircirDS.bPackup) {
        [statusTable scrollToRowAtIndexPath:indexPath
                           atScrollPosition:UITableViewScrollPositionNone
                                   animated:NO];
    }

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if ([[DataControl shareControl].fcPersonDS Curshow] != nil) {
        return [[DataControl shareControl].fcPersonDS Curshow].count;
    }
    else
    {
        return 0;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableview heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat f = [self getTheCellHeight:indexPath.row];
    return f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"StatusCell";
    StatusCell *cell = (StatusCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[StatusCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor clearColor];
        cell.contentView.backgroundColor = [UIColor clearColor];
        cell.statusContent.NumberOfLines = 0;
        cell.delegate = self;
    }
    
    NSString *strid = [[DataControl shareControl].fcPersonDS CurShowObjectByIndex:indexPath.row];
    
    if (![strid isEqualToString:@""]) {
        FriendStatus *status = [[DataControl shareControl].fcnewsDS getNewsByID:strid];
        if (status != nil) {
            cell.status = status;
            cell.imgPhoto.tag = indexPath.row;
            cell.irow = indexPath.row;
            cell.isection = indexPath.section;
            [cell reloadCell];
        }
        
        
    }
    
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([[DataControl shareControl].fcPersonDS Curshow] == nil) {
        return;
    }
    
    NSString *newid = [[DataControl shareControl].fcPersonDS CurShowObjectByIndex:indexPath.row];
    
    FriendStatus *status = [[DataControl shareControl].fcnewsDS getNewsByID:newid];
    if (status == nil) {
        return;
    }
    
    [[netManager sharedNetManager].sendFCGetAC SendFCGetALLC:status.mail
                                                  withNewsID:status.statusId];
    
    [[ViewManager sharedViewManager] setCommentsWithStatus:status];
    [[ViewManager sharedViewManager] showView:VI_STATUSCOMMENTS
                             withIsRemoveCurV:false
                                withDirection:VD_RIGHT];
}

- (CGFloat)getTheCellHeight:(int)row
{
    CGFloat height = 280;
    
    NSString *newid = [[DataControl shareControl].fcPersonDS CurShowObjectByIndex:row];
    FriendStatus *status = [[DataControl shareControl].fcnewsDS getNewsByID:newid];
    CGFloat imagehigh = 0.0f;
    
    if (status != nil) {
        
        if (status.imageIDArray.count > 0) {
            if (status.imageIDArray.count == 1) {
                NSString *picsrl = [status.imageIDArray objectAtIndex:0];
                NSString *imgUrl = [[DataControl shareControl].fcLocalRecDS getRcLocalPathByID:picsrl];
                
                if (![imgUrl isEqualToString:@""]) {
                    UIImage *image = [UIImage imageWithContentsOfFile:imgUrl];
                    CGFloat w = 1.0f;
                    CGFloat h = 1.0f;
                    if (image.size.width>280) {
                        w = image.size.width/280;
                    }
                    if (image.size.height>72) {
                        h = image.size.height/72;
                    }
                    CGFloat scole = w>h ? w:h;
                    
                    imagehigh = image.size.height/scole;
                }
            }
            else
            {
                    int iimagerow = (status.imageIDArray.count - 1) / 3  + 1;
                    imagehigh = (ARR_IMAGE_INTERVAL + ARR_IMAGE_WIDTH) * iimagerow - ARR_IMAGE_INTERVAL;
            }
            
        }
        
        if (status.stIndex == FCG_ONE_SOUND) {
            
            
            
            
            
            if (imagehigh > 0) {
                height = STATUSCELL_HEAD_HIGH +
                STATUSCELL_INTERVAL * 5 +
                STATUSCELL_SOUNDBTN_W +
                imagehigh +
                30 +
                32;
            }
            else
            {
                height = STATUSCELL_HEAD_HIGH +
                STATUSCELL_INTERVAL * 3 +
                STATUSCELL_SOUNDBTN_W +
                32;
            }
            
        }
        else
        {
            UIFont *font = [UIFont fontWithName:@"Arial" size:14];
            CGFloat contentWidth = 280;
            
            NSString *content = status.statusText;
            CGSize size = [content sizeWithFont:font
                              constrainedToSize:CGSizeMake(contentWidth, CGFLOAT_MAX)
                                  lineBreakMode:NSLineBreakByTruncatingTail];
            
            if (status.ipackuptype == PPT_NULL) {
                if (size.height > 120) {
                    size = [content sizeWithFont:font
                               constrainedToSize:CGSizeMake(contentWidth, 120)
                                   lineBreakMode:NSLineBreakByTruncatingTail];
                    
                    status.ipackuptype = PPT_SHOWMORE;
                }
                else
                {
                    status.ipackuptype = PPT_NULL;
                }
            }
            else if(status.ipackuptype == PPT_SHOWMORE)
            {
                size = [content sizeWithFont:font
                           constrainedToSize:CGSizeMake(contentWidth, 120)
                               lineBreakMode:NSLineBreakByTruncatingTail];
            }
            
            if (status.ipackuptype == PPT_NULL) {
                if (imagehigh > 0) {
                    height = STATUSCELL_HEAD_HIGH +
                    STATUSCELL_INTERVAL * 5 +
                    size.height +
                    imagehigh +
                    30 +
                    32;
                }
                else
                {
                    height = STATUSCELL_HEAD_HIGH +
                    STATUSCELL_INTERVAL * 3 +
                    size.height +
                    32;
                }
                
            }
            else
            {
                if (imagehigh > 0) {
                    height = STATUSCELL_HEAD_HIGH +
                    STATUSCELL_INTERVAL * 6 +
                    size.height +
                    32 +
                    imagehigh +
                    30 +
                    32;
                }
                else
                {
                    height = STATUSCELL_HEAD_HIGH +
                    STATUSCELL_INTERVAL * 4 +
                    size.height +
                    32 +
                    32;
                }
            }
        }
    }
    
    return height;
}


@end
